define(['modules/forms/module', 'x-editable'], function (module) {
    "use strict";

    return module.registerDirective('smartXeditable', function($timeout, $log){

    	function link (scope, element, attrs, ngModel) {
            var defaults = {
                // display: function(value, srcData) {
                //     ngModel.$setViewValue(value);
                //     // scope.$apply();
                // }
                pk: "1",
                emptytext: '空',
                success: function(response, newValue){
                    ngModel.$setViewValue(newValue);
                    scope.$apply();
                    var promise = scope.editSuccess();
                    return promise;
                    //promise.catch(function(result){
                    //    console.log(result);
                    //});
                    //return scope.editSuccess();
                },
                validate: scope.editValidate
            };

            var inited = false;

            var initXeditable = function() {

                var options = scope.options || {};
        		var initOptions = angular.extend(defaults, options);
                element.editable('destroy');
                element.editable(initOptions);
            }

            scope.$watch("options", function(newValue) {

                if(!newValue) {
                    return false;
                }

                initXeditable();

                // $log.log("Options changed...");

            }, true);
            scope.$watch(function(){
                return element[0].text;
            }, function(newValue) {
                var rValue = element.editable('getValue', true);
                if(newValue == defaults.emptytext && !rValue){
                    return;
                }
                else if(newValue){
                    element.editable('setValue', newValue);

                }
            },true);
        }

        return {
        	restrict: 'A',
        	require: "ngModel",
            scope: {
                options: '=',
                editSuccess: '=',
                editValidate: '='
            },
        	link: link 
        }
    })
});